package com.gitee.ec.kernel;

import com.gitee.ec.common.EverythingConstants;
import com.sun.jna.Native;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author hongda.li
 */
public final class EverythingLibraryAccessor {

    private static final EverythingLibrary LIBRARY;

    private EverythingLibraryAccessor() {
    }

    static {
        LIBRARY = EverythingConstants.Library.ARCH_X86_NAME.equals(EverythingConstants.Library.SYSTEM_ARCH)
                ? Native.load(EverythingConstants.Library.DLL_32_NAME, EverythingLibrary.class)
                : Native.load(EverythingConstants.Library.DLL_64_NAME, EverythingLibrary.class);
    }

    /**
     * 线程安全地访问动态链接库
     *
     * @param consumer 逻辑函数
     */
    public static synchronized void access(Consumer<EverythingLibrary> consumer) {
        Objects.requireNonNull(consumer);
        consumer.accept(LIBRARY);
    }

    /**
     * 线程安全地访问动态链接库
     *
     * @param function 逻辑函数
     * @param <T>      返回值泛型
     * @return 返回值
     */
    public static synchronized <T> T access(Function<EverythingLibrary, T> function) {
        Objects.requireNonNull(function);
        return function.apply(LIBRARY);
    }
}
